package crontab

import (
	"fmt"
	global2 "longmen/server/config/global"
	"longmen/server/internal/services/consumers/consumer/stats"
	_const "longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/common/report"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/redis/cache"
	"time"
)

func DoStatistics() {
	ipStats()
	userStats()
}

// im数据统计
func ImStats() {
	report.NewImReport().InsertDB()
}

// ipStats ip统计
func ipStats() {
	global2.Log.Info("Start ip stats")
	date := time.Now().AddDate(0, 0, -1).Format("20060102")
	total := cache.GetTotalByDate(date)
	stats := models_main.GenTodayIpStats(date)
	stats.DeviceCount = total
	err := stats.GetPlatformCount(date)
	if err != nil {
		global2.Log.Error("获取平台统计失败：", err)
	}

	err = global2.GetX().Create(&stats).Error
	if err != nil {
		global2.Log.Error("ip stats error: ", err)
		return
	}
	// 统计完成后删除数据
	global2.GetRds().Del(fmt.Sprintf(_const.GlobalCount, date))
	global2.GetRds().Del(fmt.Sprintf(_const.GlobalIpSet, date))

	//删除进直播间的数据
	global2.GetRds().Del(fmt.Sprintf(_const.GlobalLiveRoomCount, date))
	global2.GetRds().Del(fmt.Sprintf(_const.GlobalLiveRoomIpSet, date))
	cache.NewStatUserWatch().CleanupOldData()

	cache.GenDeviceIntoToCsv()

	global2.Log.Info("End ip stats")
}

// 用户统计 （注册，登录，打开）
func userStats() {
	instance := stats.NewStatistic(global2.Log)
	date := time.Now().AddDate(0, 0, -1).Format("20060102")
	err := global2.GetX().Create(instance.GetToDatabase(date)).Error
	if err != nil {
		return
	}
	instance.DeleteCache(date)
}
